package com.zrh.jsd.service.studydemo.threadpool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CompleteFutureExceptionTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(mainMethod());
    }

    private static int mainMethod() throws InterruptedException, ExecutionException {
        ExecutorService cachePool = Executors.newCachedThreadPool();
        CompletableFuture<Integer> completableFutureOne = new CompletableFuture<>();
        cachePool.submit(() -> {
            try {
                System.out.println("completableFutureOne异步任务开始====start====");
                TimeUnit.SECONDS.sleep(3);
                completableFutureOne.complete(exceptionMethod(true)); // true：抛出异常；false：正常返回值。
                System.out.println("completableFutureOne异步任务结束====end====");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        // 提交了一步任务后，主线程可以继续干一些其他的事情
        doSomeThinsElese();
        AtomicInteger result = new AtomicInteger();
        // WhenComplete 方法返回的 CompletableFuture 仍然是原来的 CompletableFuture 计算结果.
        CompletableFuture<Integer> integerCompletableFuture = completableFutureOne.whenComplete((s, throwable) -> {
            System.out.println("异步任务completableFutureOne执行完毕时打印异步任务的执行结果: s = " + s);
        });
        // 阻塞方式获取执行结果
        System.out.println("主线程结束=result== "+integerCompletableFuture.get());
        return integerCompletableFuture.get();
    }

    private static void doSomeThinsElese() throws InterruptedException {
        System.out.println("主线任务开始==doSomeThinsElese===start=");
        TimeUnit.SECONDS.sleep(3);
        System.out.println("主线任务结束==doSomeThinsElese===end=");
    }

    private static int exceptionMethod(boolean bool) throws InterruptedException {
        System.out.println("exceptionMethod===start=");
        TimeUnit.SECONDS.sleep(10);
        if(bool){
            throw new InterruptedException();
        }else{
            return 7;
        }
    }



}
